import { computed, h, reactive, ref } from "vue";
import { type GroupType, type MembersInfo, type PullGroupBasicInfo, type RecommendAndUser } from "../../types/types"
import { ElMessage, ElMessageBox, type TabsPaneContext } from 'element-plus';
import { getFriendRequestInfo, createGroup } from "../../utils/axiosApi";
import { friendStore } from "../../store/friendStore";
import { userStore } from "../../store/userStore";
import { sendAddFriend } from "../../utils/socketPageService";
import { appMounted } from "../../eventBus";
import { NIcon, type MenuOption } from "naive-ui"
import { v4 as uuidv4 } from 'uuid';
import { BookmarkOutline } from "@vicons/ionicons5";


type ToolBar = {
    label: string,
    icon: string,
    url?: string,
    key?: string
}

let user_store: ReturnType<typeof userStore> | null = null;
let friend_store: ReturnType<typeof friendStore> | null = null;

// 全局检测pinia是否挂载完毕，避免后期使用出现错误
function checkAppMounted() {
    if (appMounted.value) {
        // 挂载完毕，创建pinia store实例对象
        user_store = userStore();
        friend_store = friendStore();
    } else {
        // 挂载失败就使用计时器检查
        setTimeout(checkAppMounted, 100);
    }
}
checkAppMounted();

export const toolBarMenus: ToolBar[] = reactive([
    // { label: "返回", icon: getIconUrl("../../assets/General/back.svg"), url: "/back", key: '/back' },
    // { label: "Chat", icon: getIconUrl("../../assets/General/menu/search-message.svg"), url: "ASIDE-MENU-CHAT", key: '/chat' },
    // { label: "联系人", icon: getIconUrl("../../assets/General/socket/user-manager.svg"), url: "ASIDE-MENU-CONTACT", key: "/contact" },
    { label: "音乐", icon: getIconUrl("../../assets/General/menu/music-albums.svg"), url: "ASIDE-MENU-MUSIC", key: '/music' },
    // { label: "博客", icon: getIconUrl("../../assets/General/menu/blog.svg"), url: "ASIDE-MENU-BLOG", key: '/blog' },
    { label: "空间", icon: getIconUrl("../../assets/General/space.svg"), url: "ASIDE-MENU-SPACE", key: "/space" },
    { label: "收藏", icon: getIconUrl("../../assets/General/collection.svg"), url: "ASIDE-MENU-COLLECTION", key: '/collection' },
    { label: "文件", icon: getIconUrl("../../assets/General/menu/files.svg"), url: "ASIDE-MENU-FILE", key: '/file' },
    { label: "装扮", icon: getIconUrl("../../assets/General/personal-setyle-decoration.svg"), url: "ASIDE-MENU-DECORATION", key: '/decoration' },
    { label: "设置", icon: getIconUrl("../../assets/General/setting.svg"), url: "ASIDE-MENU-SETTING", key: '/setting' },
])

// 定义菜单
export const menuOptions: MenuOption[] = [
    { label: "", key: "ASIDE-MENU-MUSIC", href: getIconUrl("../../assets/General/menu/music-albums.svg") },
    // { label: "", key: "ASIDE-MENU-SPACE", href: getIconUrl("../../assets/General/space.svg") },
    // { label: "", key: "ASIDE-MENU-COLLECTION", href: getIconUrl("../../assets/General/collection.svg") },
    // { label: "", key: "ASIDE-MENU-FILE", href: getIconUrl("../../assets/General/menu/files.svg") },
    { label: "", key: "ASIDE-MENU-DECORATION", href: getIconUrl("../../assets/General/personal-setyle-decoration.svg") },
    { label: "", key: "ASIDE-MENU-SETTING", href: getIconUrl("../../assets/General/setting.svg") },
]
export function renderMenuIcon(option: MenuOption) {
    // 渲染图标占位符以保持缩进
    if (option.key === 'sheep-main') return true;
    if (option.key === 'food') return null;
    return h('img', { src: option.href, width: 24, height: 24 })
}


function getIconUrl(path: string): string {
    return new URL(path, import.meta.url).href;
}

// 控制显示联系人信息
export const showContactInfo = ref<boolean>(false);
// 控制展示菜单信息
export const showToolBarMenu = ref<boolean>(false);



// 对菜单进行分页
const itemsPerPage = ref<number>(3);
const totalPages = computed(() => Math.ceil(toolBarMenus.length / itemsPerPage.value));
export const paginatedMenus = computed(() => {
    const pages = [];
    for (let i = 0; i < totalPages.value; i++) {
        const start = i * itemsPerPage.value;
        const end = start + itemsPerPage.value;
        pages.push(toolBarMenus.slice(start, end));
    }
    return pages;
})

// el-tabs点击处理事件
export let currentActiveTab = ref<string>("request");
export const handleTabClick = (tab: TabsPaneContext, event: Event): void => {
    currentActiveTab.value = tab.props.name as string;
}

// 获取好友请求信息
export function getRequestInfo() {
    // 延迟调用pinia store
    const friend_store = friendStore();
    getFriendRequestInfo().then((data): void => {
        if (data != undefined) {
            friend_store.setFriendRequestList(data);
        } else {
            // 暂无好友申请信息
            return;
        }
    }).catch((error): void => {
        console.error(error);
    })
}

// 控制展示好友详细信息
export const currentDetailsInfo = ref<any>({});
export const showDetailStatus = ref<boolean>(false);
export function switchDetailStatus(friend: RecommendAndUser) {
    currentDetailsInfo.value = friend;
    showDetailStatus.value = !showDetailStatus.value;
}



// 模拟添加好友信息输入框
export const addFriend = (websocket: WebSocket, friend: any): void => {
    user_store = userStore();
    ElMessageBox.prompt('输入问候语（支持默认值、空值、自定义）', '好友申请', {
        confirmButtonText: 'sure',
        cancelButtonText: 'cancel',
        inputPlaceholder: "1111",
        inputValue: `你好，我是：${user_store.userInfo.username}` as string
    }).then(({ value }) => {
        const addFriendInfo = {
            toChatId: friend.uu_id,
            content: value,
            messageType: "add_friend_request"
        }
        sendAddFriend(websocket, addFriendInfo);
    }).catch((error): void => {
        ElMessage.error(`信息发送失败：${error}`);
    })
}




// 存储transfer信息
export const infoValue = ref<any[]>([]);



export const groupTypes: GroupType[] = reactive([
    {
        label: "学习", url: "/study", icon: "11", subTypes: [
            { label: "编程", url: "/study/programming", icon: "11a" },
            { label: "数学", url: "/study/math", icon: "11b" },
            { label: "科学", url: "/study/science", icon: "11c" }
        ]
    },
    {
        label: "工作", url: "/work", icon: "22", subTypes: [
            { label: "项目管理", url: "/work/project-management", icon: "22a" },
            { label: "开发", url: "/work/development", icon: "22b" },
            { label: "设计", url: "/work/design", icon: "22c" }
        ]
    },
    {
        label: "生活", url: "/life", icon: "33", subTypes: [
            { label: "健康", url: "/life/health", icon: "33a" },
            { label: "饮食", url: "/life/diet", icon: "33b" },
            { label: "睡眠", url: "/life/sleep", icon: "33c" }
        ]
    },
    {
        label: "娱乐", url: "/entertainment", icon: "44", subTypes: [
            { label: "电影", url: "/entertainment/movies", icon: "44a" },
            { label: "音乐", url: "/entertainment/music", icon: "44b" },
            { label: "游戏", url: "/entertainment/games", icon: "44c" }
        ]
    },
    {
        label: "运动", url: "/sports", icon: "55", subTypes: [
            { label: "跑步", url: "/sports/running", icon: "55a" },
            { label: "游泳", url: "/sports/swimming", icon: "55b" },
            { label: "篮球", url: "/sports/basketball", icon: "55c" }
        ]
    },
    {
        label: "社交", url: "/social", icon: "66", subTypes: [
            { label: "朋友", url: "/social/friends", icon: "66a" },
            { label: "家人", url: "/social/family", icon: "66b" },
            { label: "同事", url: "/social/colleagues", icon: "66c" }
        ]
    },
    {
        label: "其他", url: "/other", icon: "77", subTypes: [
            { label: "未分类", url: "/other/unclassified", icon: "77a" }
        ]
    }
]);
// 存储创建群聊基本信息的变量
export const pullGroupInfo: PullGroupBasicInfo = reactive({
    group_name: "测试群聊1",
    group_type: "",
    group_members: [],
    group_leader: "",
    group_id: uuidv4()
})
// 检查string[]长度
function checkNonEmptyArrayLength(arr: MembersInfo[], arrayLength: number): boolean {
    // 过滤空字符串
    return arr.length >= arrayLength;
}
// 拉取群聊的函数
export function pullGroupChats(groupType?: string) {
    if (groupType === 'pull') {
        if (!user_store?.userInfo.uu_id || !user_store.userInfo.username || !user_store.userInfo.avatar) {
            ElMessage.error("无法获取当前用户信息");
            return;
        }
        // 将当前用户也添加到群聊中 ，这是必须存在的        其实就是群主信息
        const leader: MembersInfo = {
            key: user_store?.userInfo.uu_id,
            label: user_store?.userInfo.username,
            avatar: user_store?.userInfo.avatar
        };
        // 将当前用户也添加到群聊中     因为groupMembers可能是undefined
        pullGroupInfo.group_members!.push(leader);
        // 去重操作
        pullGroupInfo.group_members = Array.from(new Set(pullGroupInfo.group_members));
        // 设置群主信息
        pullGroupInfo.group_leader = leader.key;
        // 检查群成员
        if (checkNonEmptyArrayLength(pullGroupInfo.group_members, 2)) {
            // 向后端发送创建群聊的功能
            // 二次检测消息
            if (pullGroupInfo.group_name.trim() === "" || pullGroupInfo.group_type.trim() === "") {
                ElMessage.warning("群聊基本信息不能为空！");
            } else {
                createGroup(leader.key, pullGroupInfo);
            }
        } else {
            ElMessage.error("群成员至少两位");
        }
    } else {
        // 清空群聊信息     等同于重置信息
        pullGroupInfo.group_name = "";
        pullGroupInfo.group_type = "";
        pullGroupInfo.group_members = [];
        pullGroupInfo.group_leader = "";
        pullGroupInfo.group_id = uuidv4();
        infoValue.value = [];
    }
}
